<?php

/**
 * ECSHOP 管理中心供货商管理
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: wanglei $
 * $Id: suppliers.php 15013 2009-05-13 09:31:42Z wanglei $
 */

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
include_once(ROOT_PATH . '/includes/cls_image.php');
// $image = new cls_image($_CFG['bgcolor']);
/* 允许上传的文件类型 */
$allow_file_types = '|GIF|JPG|PNG|BMP|';
define('SUPPLIERS_ACTION_LIST', 'delivery_view,back_view');
/*------------------------------------------------------ */
//-- 供货商列表
/*------------------------------------------------------ */
if ($_REQUEST['act'] == 'list')
{
     /* 检查权限 */
     admin_priv('suppliers_manage');

    /* 查询 */
    $result = suppliers_list();

	
	$types = isset($_GET['types']) ? intval($_GET['types']) : 1;
    /* 模板赋值 */
    $smarty->assign('ur_here', $_LANG['suppliers_list']); // 当前导航
    $smarty->assign('action_link', array('href' => 'sheep.php?act=add&types='.$types, 'text' => $_LANG['add_suppliers']));

    $smarty->assign('full_page',        1); // 翻页参数

    $smarty->assign('types',    $types);
    $smarty->assign('sheep_list',    $result['result']);
    $smarty->assign('filter',       $result['filter']);
    $smarty->assign('record_count', $result['record_count']);
    $smarty->assign('page_count',   $result['page_count']);
    $smarty->assign('sort_suppliers_id', '<img src="images/sort_desc.gif">');

    /* 显示模板 */
    assign_query_info();
    $smarty->display('sheep_list.htm');
}

/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    check_authz_json('suppliers_manage');

    $result = suppliers_list();

    $smarty->assign('sheep_list',    $result['result']);
    $smarty->assign('filter',       $result['filter']);
    $smarty->assign('record_count', $result['record_count']);
    $smarty->assign('page_count',   $result['page_count']);

    /* 排序标记 */
    $sort_flag  = sort_flag($result['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch('sheep_list.htm'), '',
        array('filter' => $result['filter'], 'page_count' => $result['page_count']));
}

/*------------------------------------------------------ */
//-- 列表页编辑名称
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_sheep_name')
{
    check_authz_json('suppliers_manage');

    $id     = intval($_POST['id']);
    $name   = json_str_iconv(trim($_POST['val']));

   
        /* 保存供货商信息 */
        $sql = "UPDATE " . $ecs->table('sheep') . "
                SET sheep_name = '$name'
                WHERE sheep_id = '$id'";
        if ($result = $db->query($sql))
        {
            /* 记日志 */
            admin_log($name, 'edit', 'sheep');

            clear_cache_files();

            make_json_result(stripslashes($name));
        }
        else
        {
            make_json_result(sprintf($_LANG['agency_edit_fail'], $name));
        }
     
}

/*------------------------------------------------------ */
//-- 删除供货商
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{
    check_authz_json('suppliers_manage');

    $id = intval($_REQUEST['id']);
    $sql = "SELECT *
            FROM " . $ecs->table('sheep') . "
            WHERE sheep_id = '$id'";
    $sheep = $db->getRow($sql, TRUE);

    if ($sheep['sheep_id'])
    {
        $sql = "DELETE FROM " . $ecs->table('sheep') . "
            WHERE sheep_id = '$id'";
        $db->query($sql);
        /* 记日志 */
        admin_log($sheep['sheep_name'], 'remove', 'sheep');

        /* 清除缓存 */
        clear_cache_files();
    }

    $url = 'sheep.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);
    ecs_header("Location: $url\n");

    exit;
}

/*------------------------------------------------------ */
//-- 修改供货商状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'is_check')
{
    check_authz_json('suppliers_manage');

    $id = intval($_REQUEST['id']);
    $sql = "SELECT suppliers_id, is_check
            FROM " . $ecs->table('suppliers') . "
            WHERE suppliers_id = '$id'";
    $suppliers = $db->getRow($sql, TRUE);

    if ($suppliers['suppliers_id'])
    {
        $_suppliers['is_check'] = empty($suppliers['is_check']) ? 1 : 0;
        $db->autoExecute($ecs->table('suppliers'), $_suppliers, '', "suppliers_id = '$id'");
        clear_cache_files();
        make_json_result($_suppliers['is_check']);
    }

    exit;
}

/*------------------------------------------------------ */
//-- 批量操作
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'batch')
{
    /* 取得要操作的记录编号 */
    if (empty($_POST['checkboxes']))
    {
        sys_msg($_LANG['no_record_selected']);
    }
    else
    {
        /* 检查权限 */
        admin_priv('suppliers_manage');

        $ids = $_POST['checkboxes'];

        if (isset($_POST['remove']))
        {
            $sql = "SELECT *
                    FROM " . $ecs->table('sheep') . "
                    WHERE sheep_id " . db_create_in($ids);
            $sheep = $db->getAll($sql);
 
            if (empty($sheep))
            {
                sys_msg($_LANG['batch_drop_no']);
            }


            $sql = "DELETE FROM " . $ecs->table('sheep') . "
                WHERE sheep_id " . db_create_in($ids);
            $db->query($sql);

          
            /* 记日志 */
            $suppliers_names = '';
            foreach ($sheep as $value)
            {
                $suppliers_names .= $value['sheep_name'] . '|';
            }
            admin_log($suppliers_names, 'remove', 'sheep');

            /* 清除缓存 */
            clear_cache_files();

            sys_msg($_LANG['batch_drop_ok']);
        }
    }
}

/*------------------------------------------------------ */
//-- 添加、编辑供货商
/*------------------------------------------------------ */
elseif (in_array($_REQUEST['act'], array('add', 'edit')))
{
    /* 检查权限 */
    admin_priv('suppliers_manage');

	
	$types = isset($_GET['types']) ? intval($_GET['types']) : 1;
	$smarty->assign('types', $types);
    if ($_REQUEST['act'] == 'add')
    {
  

        assign_query_info();
		$smarty->assign('ur_here', $_LANG['edit_suppliers']);
        $smarty->assign('action_link', array('href' => 'sheep.php?act=list&types='.$types, 'text' => $_LANG['suppliers_list']));

        $smarty->assign('form_action', 'insert');
		$sheep = array();
		$sheep['types'] = $types;
		$smarty->assign('sheep', $sheep);
        $smarty->display('sheep_info.htm');

    }
    elseif ($_REQUEST['act'] == 'edit')
    {
        $sheep = array();

        /* 取得供货商信息 */
        $id = $_REQUEST['id'];
        $sql = "SELECT * FROM " . $ecs->table('sheep') . " WHERE sheep_id = '$id'";
        $sheep = $db->getRow($sql);
   
        $smarty->assign('ur_here', $_LANG['edit_suppliers']);
        $smarty->assign('action_link', array('href' => 'sheep.php?act=list&types='.$types, 'text' => $_LANG['suppliers_list']));
		
        $smarty->assign('form_action', 'update');
		
		$sheep['start_date'] = local_date('Y-m-d H:i', $sheep['start_date']);
        $sheep['end_date'] = local_date('Y-m-d H:i', $sheep['end_date']);
 
        $smarty->assign('sheep', $sheep);
	
        assign_query_info();

        $smarty->display('sheep_info.htm');
    }

}

/*------------------------------------------------------ */
//-- 提交添加、编辑供货商
/*------------------------------------------------------ */
elseif (in_array($_REQUEST['act'], array('insert', 'update')))
{
    /* 检查权限 */
    admin_priv('suppliers_manage');

 /* 取得文件地址 */
    $logo_img = '';
    if ((isset($_FILES['logo_img']['error']) && $_FILES['logo_img']['error'] == 0) || (!isset($_FILES['logo_img']['error']) && isset($_FILES['logo_img']['tmp_name']) && $_FILES['logo_img']['tmp_name'] != 'none'))
    {
        // 检查文件格式
        if (!check_file_type($_FILES['logo_img']['tmp_name'], $_FILES['logo_img']['name'], $allow_file_types))
        {
            sys_msg($_LANG['invalid_file']);
        }

        // 复制文件
        $res = upload_sheep_file($_FILES['logo_img']);
        if ($res != false)
        {
            $logo_img = $res;
        }
    }
	if(empty($logo_img)){
		$logo_img = trim($_POST['logo_imgs']);
	}

    if ($_REQUEST['act'] == 'insert')
    {
        /* 提交值 */
        $sheep = array('sheep_name'   => trim($_POST['sheep_name']),
                           'qishu'   => intval($_POST['qishu']),
                           'price'   => trim($_POST['price']),
                           'bonus'   => trim($_POST['bonus']),
                           'types'   => intval($_POST['types']),
                           'jiazhi'   => intval($_POST['jiazhi']),
                           'sheep_pinzhong'   => trim($_POST['sheep_pinzhong']),
                           'cycle'   => trim($_POST['cycle']),
                           'number'   => intval($_POST['number']),
                           'end_date'   => local_strtotime($_POST['end_date']),
                           'start_date'   => local_strtotime($_POST['start_date']),
                           'add_time'   =>  gmtime(),
                           'logo_img'   =>  $logo_img
                           );
						   
		
 
        /* 判断期数是否重复 */
        $sql = "SELECT qishu
                FROM " . $ecs->table('sheep') . "
                WHERE qishu = '" . $sheep['qishu'] . "' and  types = '". $sheep['types']  ."'";
        if ($db->getOne($sql))
        {
            sys_msg("期数已存在");
        }
		 
        $db->autoExecute($ecs->table('sheep'), $sheep, 'INSERT');
        $sheep['sheep_id'] = $db->insert_id();

		/* 新羊 上线通知  S */
		$sql = "select u.wxid from " . $ecs->table('users') ." as u LEFT JOIN  " . $ecs->table('weixin_user')." AS w ON w.wxid = u.wxid where u.mobile_phone != '' and u.wxid != '' and w.subscribe = 1  and u.yz_xy_msg = 1 " ;
		$user = $db->getAll($sql);
		if($user){
			foreach($user as $k => $v){
				wx_msg($v['wxid'],2,$sheep);
			}
		}
		/* 新羊 上线通知  E */
        /* 记日志 */
        admin_log($suppliers['sheep_name'], 'add', 'sheep');

        /* 清除缓存 */
        clear_cache_files();

        /* 提示信息 */
        $links = array(array('href' => 'sheep.php?act=add&types='. $sheep['types'] ,  'text' => $_LANG['continue_add_suppliers']),
                       array('href' => 'sheep.php?act=list&types='. $sheep['types'], 'text' => $_LANG['back_suppliers_list'])
                       );
        sys_msg($_LANG['add_suppliers_ok'], 0, $links);

    }

    if ($_REQUEST['act'] == 'update')
    {
        /* 提交值 */
        $sheep = array('id'   => trim($_POST['id']));

		/* 提交值 */
        $sheep['new'] = array(
			'sheep_name'   => trim($_POST['sheep_name']),
			// 'qishu'   => intval($_POST['qishu']),
			'price'   => trim($_POST['price']),
			'bonus'   => trim($_POST['bonus']),
			'jiazhi'   => trim($_POST['jiazhi']),
			'sheep_pinzhong'   => trim($_POST['sheep_pinzhong']),
			'cycle'   => trim($_POST['cycle']),
			'number'   => intval($_POST['number']),
			'end_date'   => local_strtotime($_POST['end_date']),
			'start_date'   => local_strtotime($_POST['start_date']),
			'logo_img'   =>  $logo_img
		   );
		   
		   
        /* 判断名称是否重复 */
        // $sql = "SELECT sheep_id
                // FROM " . $ecs->table('sheep') . "
                // WHERE qishu = '" . $sheep['new']['qishu'] . "'
                // AND sheep_id <> '" . $sheep['id'] . "' ";
        // if ($db->getOne($sql))
        // {
            // sys_msg("期数重复");
        // }

        /* 保存供货商信息 */
        $db->autoExecute($ecs->table('sheep'), $sheep['new'], 'UPDATE', "sheep_id = '" . $sheep['id'] . "'");

    
 
        /* 记日志 */
        admin_log($sheep['old']['sheep_name'], 'edit', 'sheep');

        /* 清除缓存 */
        clear_cache_files();

        /* 提示信息 */
        $links[] = array('href' => 'sheep.php?act=list&types='. $_POST['types'], 'text' => $_LANG['back_suppliers_list']);
        sys_msg($_LANG['edit_suppliers_ok'], 0, $links);
    }

}

/**
 *  获取供应商列表信息
 *
 * @access  public
 * @param
 *
 * @return void
 */
function suppliers_list()
{
    $result = get_filter();
    if ($result === false)
    {
        $aiax = isset($_GET['is_ajax']) ? $_GET['is_ajax'] : 0;
        $types = !empty($_GET['types']) ? intval($_GET['types']) : 1;

        /* 过滤信息 */
        $filter['sort_by'] = empty($_REQUEST['sort_by']) ? 'sheep_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

        $where = 'WHERE 1 and types = '. $types;

        /* 分页大小 */
        $filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);

        if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
        {
            $filter['page_size'] = intval($_REQUEST['page_size']);
        }
        elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
        {
            $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
        }
        else
        {
            $filter['page_size'] = 15;
        }

	 
		
        /* 记录总数 */
        $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('sheep') . $where;
        $filter['record_count']   = $GLOBALS['db']->getOne($sql);
        $filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;

        /* 查询 */
        $sql = "SELECT *
                FROM " . $GLOBALS['ecs']->table("sheep") . "
                $where
                ORDER BY " . $filter['sort_by'] . " " . $filter['sort_order']. "
                LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ", " . $filter['page_size'] . " ";

        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }

    $row = $GLOBALS['db']->getAll($sql);

    $arr = array('result' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

    return $arr;
}

/* 上传文件 */
function upload_sheep_file($upload)
{
    if (!make_dir("../" . DATA_DIR . "/sheep"))
    {
        /* 创建目录失败 */
        return false;
    }

    $filename = cls_image::random_filename() . substr($upload['name'], strpos($upload['name'], '.'));
    $path     = ROOT_PATH. DATA_DIR . "/sheep/" . $filename;

    if (move_upload_file($upload['tmp_name'], $path))
    {
        return DATA_DIR . "/sheep/" . $filename;
    }
    else
    {
        return false;
    }
}

?>